package judger

import (
	"gugojudger/env"
	"strconv"
	"time"
)

// JudgerByMQ 获取消息队列中的数据并开始判题
func JudgerByMQ(queue chan *Question, succ chan *OJResult) {
	var sem = make(chan int, env.GetMaxJudge())
	for req := range queue {
		sem <- 1
		req := req
		go func() {
			res := JudgerByContent(req.Content, req.Testcase, int64(req.LimitTime), int64(req.LimitMemory), COMPILER(req.Lang))
			res.ID = req.ID
			succ <- res
			<-sem
		}()
	}
}

// JudgerByContent 直接根据代码进行判题
func JudgerByContent(content string, testcase []TestCase, limitTime int64, limitMem int64, LANG COMPILER) *OJResult {
	var result OJResult

	res := StrCompiler(content, LANG)
	result.Lang = LANG
	if res.Status == false {
		result.Compiler = STATE(res.Code)
		result.Message = res.Data["msg"]
		return &result
	}
	result.Compiler = AFG_CC
	dirPath := res.Data["msg"]

	for i := 0; i < len(testcase); i++ {
		res = Judge_TR(dirPath, testcase[i].Stdin)
		if res.Code < AFG_CC {
			result.TestResult = append(result.TestResult, TestResult{STATE(res.Code), 0, 0, ""})
			continue
		}
		tim, _ := strconv.ParseFloat(res.Data["time"], 64)
		mem, _ := strconv.ParseFloat(res.Data["memory"], 64)
		result.TestResult = append(result.TestResult, TestResult{
			Contrast(res.Data["stdout"], testcase[i].Stdout, int64(tim), limitTime, int64(mem), limitMem),
			tim,
			mem,
			res.Data["stdout"]})
		time.Sleep(time.Millisecond * 30)
	}
	removeTarget(dirPath)
	return &result
}
